import {
	http
} from './request.js';

// 通用相关API
export const commonApi = {
	// 上传单个文件（通用）
	uploadFile(filePath) {
		return new Promise((resolve, reject) => {
			const token = uni.getStorageSync('token');
			uni.uploadFile({
				url: 'http://localhost:1750/api/common/user/upload',
				filePath: filePath,
				name: 'file',
				header: {
					'Authorization': token,
					// multipart/form-data header is set automatically by uni.uploadFile
				},
				formData: {
					// 可以添加额外参数
					'type': 'review'
				},
				success: (uploadFileRes) => {
					console.log('上传结果:', uploadFileRes);
					try {
						const result = JSON.parse(uploadFileRes.data);
						if (result.code === 200) {
							resolve(result.data); // 返回文件URL
						} else {
							console.error('上传失败:', result);
							reject(new Error(result.msg || '上传失败'));
						}
					} catch (e) {
						console.error('解析上传结果失败:', e, uploadFileRes);
						reject(new Error('解析上传结果失败'));
					}
				},
				fail: (err) => {
					console.error('文件上传失败:', err);
					reject(new Error('文件上传失败: ' + (err.errMsg || JSON.stringify(err))));
				}
			});
		});
	},

	// 批量上传图片
	uploadImages(fileList) {
		const promises = fileList.map(filePath => this.uploadFile(filePath));
		return Promise.all(promises);
	}
};